import { invoke } from "@tauri-apps/api/core";
import { Category } from "@/types/category";
import { AppItem } from "@/types/app";
import { retryOperation } from "../utils";

export const getAllCategories = async (): Promise<Category[]> => {
  try {
    return await retryOperation(async () => {
      return await invoke<Category[]>("get_all_categories");
    });
  } catch (error) {
    console.error("获取分类列表失败:", error);
    throw new Error("获取分类列表失败");
  }
};

export const getCategoryApps = async (categoryId: string): Promise<AppItem[]> => {
  // 从后端获取数据并转换字段名称
  try {
    const rawApps = await retryOperation(async () => {
      return await invoke<Array<{
        More: string,
        Name: string,
        Pkgname: string,
        Tags?: string,
        Update: string,
        icon?: string,
        category?: string
      }>>("get_category_apps", { categoryId });
    });

    // 将后端返回的大写字段名转换为前端使用的小写格式
    return rawApps.map(app => ({
      more: app.More,
      name: app.Name,
      pkgname: app.Pkgname,
      tags: app.Tags,
      update: app.Update,
      icon: app.icon,
      category: app.category
    }));
  } catch (error) {
    console.error("获取分类应用列表失败:", error);
    throw new Error("获取分类应用列表失败");
  }
};